<script setup>
import { computed, ref, reactive, onActivated } from "vue";
import { ApiAddUser, getRole, addgroup } from "@/api/user";
import { toast } from "@/hook/toast";

const emits = defineEmits(['success'])
function open(row) {


    visible.value = true
    const { id } = row
    formData.user_id = id
}
const visible = ref(false)
defineExpose({
    open,
})
const formData = reactive({
    // 客户资料
    shenfen_id: '',
    user_id: ''
});

const roleOption = computed(() => {
    return roleOptions.value.map(item => ({
        label: item.rank_name,
        value: item.id
    }))
})
const roleOptions = ref([])
const formRules = computed(() => {
    return {
        shenfen_id: [
            {
                required: true,
                message: '请选择身份',
                trigger: 'blur'
            }
        ]
    }
})
const formRef = ref(null)

// 获取用户角色展示
async function initData() {
    // getRole
    const resp = await getRole().catch(() => {
    });
    const { code, data } = resp;
    if (code !== 1) return;
    roleOptions.value = data;
    console.log(roleOptions.value, '数据展示');
}
onActivated(() => {
    initData()
})

function cancelHandle() {
    visible.value = false
}

function addHandle() {
    formRef.value.validate(async flag => {
        if (!flag) return
        const { shenfen_id, user_id } = formData
        const submit = { shenfen_id, user_id }
        const resp = await addgroup(submit)
        const { code, msg } = resp
        toast({
            title: msg,
            type: code === 1 ? 'success' : 'error',
        })
        if (code !== 1) return
        emits('success')
        visible.value = false
    })
}

function resetForm() {
    formRef.value.resetFields()
}

</script>

<template>
    <el-drawer v-model="visible" title="绑定身份" size="500px" @closed="resetForm">
        <el-form ref="formRef" :model="formData" label-position="left" label-width="80px" :rules="formRules">
            <el-form-item label="身份" prop="shenfen_id">
                <el-select placeholder="请选择身份" v-model="formData.shenfen_id">
                    <el-option v-for="(item, index) in roleOption" :key="index" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-space>
                <el-button type="info" @click="cancelHandle">取消</el-button>
                <el-button type="primary" @click="addHandle">确认修改</el-button>
            </el-space>
        </template>
    </el-drawer>
</template>

<style scoped lang="scss"></style>
